#include "ColladaTextureData.h"

namespace lib3dw
{
	ColladaTextureData::ColladaTextureData(FCDocument* colladaDocument)
	{
		FCDImageLibrary *library = colladaDocument->GetImageLibrary();
		ProcessImageLibrary(library); 
	}
	
	ColladaTextureData::~ColladaTextureData()
	{

	}
	
	const GLuint* ColladaTextureData::GetTexture(unsigned short index) const
	{
		return &textures[index];
	}
		
	void ColladaTextureData::SetTextureCount(unsigned int texCount)
	{
		textureCount = texCount;
	}
	
	void ColladaTextureData::ProcessImageLibrary(FCDImageLibrary* library)
	{
		//HACK we only support one texture at the moment - textCount should contain: library->GetEntityCount()
		unsigned int texCount =  1;

		SetTextureCount(texCount);
		for (unsigned int textureIndex = 0; textureIndex < texCount; textureIndex++)
		{
			FCDImage *image = library->GetEntity(textureIndex);
			fstring FCDfilename= image->GetFilename();
			unsigned int size = FCDfilename.size();
			char *fn = new char[size + 1];
	
			unsigned int charIndex;
			for (charIndex = 0; charIndex < size; charIndex++)
			{
				fn[charIndex] = FCDfilename.c_str()[charIndex];
			}
			
			//HACK terminate after the first image, we only support one texture
			fn[charIndex] = '\0';

			std::string textureFilename = std::string(fn);
			PNGTexture* currentTexture = NULL;
			std::map<std::string, PNGTexture*>* loadedTextures = TextureProxySingleton::Instance()->GetLoadedTextures();
			if((*loadedTextures)[textureFilename] == NULL)
			{
				currentTexture = new PNGTexture(textureFilename.c_str(), textureFilename.c_str());
				(*loadedTextures)[textureFilename] = currentTexture;
			}
			textures.push_back((*loadedTextures)[textureFilename]->GetId());
		}
	}
}